﻿using MediatR;
using Sowrk03_28.Repository;
using Swork03_28.Api.Application.Commands.FarmedCommand;
using Swork03_28.Domain.TraceableInfos;
using Swork03_28.Services.Impls;
using Swork03_28.Services.Interface;

namespace Swork03_28.Api.Application.CommandHandlers.FarmedHandler
{
    public class FirmImgCreateCommandHandler : IRequestHandler<FirmImgCreateCommand, int>
    {
        private readonly IRepository<FirmInfo> _firmInfo;
        private readonly IFarmedService farmedService;

        public FirmImgCreateCommandHandler(IRepository<FirmInfo> repository, IFarmedService farmedService)
        {
            this._firmInfo = repository;
            this.farmedService = farmedService;
        }

        public async Task<int> Handle(FirmImgCreateCommand request, CancellationToken cancellationToken)
        {
            var count = 0;
            var info = await _firmInfo.GetValues(x => x.BatchId == request.BatchId && x.FirmType == FirmType.养殖公司);
            var res = info.FirstOrDefault();
            if (res == null)
            {
                count += await _firmInfo.CreateAsync(new FirmInfo()
                {
                    BatchId = request.BatchId,
                    CampanyImage = request.Imgs
                });
                var firm = await _firmInfo.GetValues(x => x.BatchId == request.BatchId);
                var id = firm.FirstOrDefault().Id;
                await farmedService.CreateAsync(new Farmed()
                {
                    FarmId = id,
                    BatchId = request.BatchId,
                    Brand = null,
                    Principal = null,
                    Breed = null,
                    Certificate = null,
                    Feeding = 0,
                    PublicationDate = null,
                    Source = null
                });
            }
            else
            {
                res.CampanyImage = (res.CampanyImage + "," + request.Imgs).TrimStart(",".ToCharArray()).TrimEnd(",".ToCharArray());
                count += await _firmInfo.UpdateAsync(res);
            }
            return count;
        }
    }
}
